import { useState, useEffect } from 'react';
import { Drawer, Button, Form, Table, Link, Popconfirm, Space, Input, Message } from '@arco-design/web-react';
import { fetchButtonList, fetchChangeModuleStatus, fetchModuleDelete, fetchModuleAdd } from '../../../../../api/common';
import { regExpConfig } from '../../../../../configs/regular.config'
const formItemLayout = {
  wrapperCol: {
    span: 24,
  },
};
function ButtonModal({state, setState}) {
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [buttonModify, setButtonModify] = useState({
    visiable: false,
    data: {
        resKey: '1',
        resName: '1',
        sort: 0
    }
  })
  const [buttonAdd, setButtonAdd] = useState({
    visiable: false,
  })
  const [keyIterater, next] = useState(2345)

  const columns = [
    {
        title: '按钮名称',
        dataIndex: 'resName',
        key: 'resName',
        width: '40%',
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: '20%',
        render: (text, record, index) => {
          if (record.status === 1) {
            return <Link status='error'>未上线</Link>
          }
          return <Link status='success'>已上线</Link>
        }
    },
    {
        title: '操作',
        dataIndex: 'caozuo',
        key: 'caozuo',
        width: '40%',
        render: (text, record, index) => (
          <span>
            <Popconfirm
                focusLock
                title={`确认${record.status === 1 ? '上线' : '下线'}？`}
                content=''
                onOk={() => {
                  showOrHiden(record.id, record.status)
                }}
                onCancel={() => {
                // Message.error({
                //     content: 'cancel',
                // });
                }}>
                <Button type='text' style={{padding: '0'}}>
                  { record.status === 1 ? '上线' : '下线' }
                </Button>|
            </Popconfirm>
            <Button type='text' style={{padding: '0'}} 
                    onClick={()=>{
                        setButtonModify(
                            {
                              visiable: true, 
                              data: {
                                  id: record.id,
                                  resName: record.resName,
                                  resKey: record.resKey,
                                  sort: record.sort
                              } 
                            })
                    }}>修改</Button>|
            <Popconfirm
                focusLock
                title='确认删除？'
                content=''
                onOk={() => {
                  buttonDelet(record.id)
                }}
                onCancel={() => {
                // Message.error({
                //     content: 'cancel',
                // });
                }}>
                <Button type='text' style={{padding: '0'}}>删除</Button>
            </Popconfirm>
          </span>
        ),
    }
  ];

  function showOrHiden(id, status){
    fetchChangeModuleStatus({id: id, status: status},
      (resp)=>{
        // state.buttonModal.buttonList.loading
        setState(state=>{
          return{
            ...state,
            buttonModal: {
              ...state.buttonModal,
              buttonList: {
                ...state.buttonModal.buttonList,
                loading: true
              }
            }
          }
        })
        let tmp = [...state.buttonModal.buttonList.data]
        if (tmp && tmp.length > 0){
          for (let i = 0; i < tmp.length; i++){
            if(tmp[i].id == id){
              tmp[i] = {
                ...tmp[i],
                status: tmp[i].status == 0 ? 1 : 0
              }
            }
          }
        }   
        setState(state=>{
          return{
            ...state,
          buttonModal: {
            ...state.buttonModal,
            buttonList: {
              ...state.buttonModal.buttonList,
              data: tmp
            }
          }
          }
        })
        Message.success('修改成功')
        setState(state=>{
          return{
            ...state,
            buttonModal: {
              ...state.buttonModal,
              buttonList: {
                ...state.buttonModal.buttonList,
                loading: false
              }
            }
          }
        })
      },
      ()=>{
        Message.error('修改失败')
        setState(state=>{
          return{
            ...state,
            buttonModal: {
              ...state.buttonModal,
              buttonList: {
                ...state.buttonModal.buttonList,
                loading: false
              }
            }
          }
        })
      })
  }

  function buttonDelet(id){
    fetchModuleDelete({id: id},
      ()=>{
        setState(state=>{
          return{
            ...state,
            buttonModal: {
              ...state.buttonModal,
              buttonList: {
                ...state.buttonModal.buttonList,
                loading: true
              }
            }
          }
        })
        let tmp = [...state.buttonModal.buttonList.data]
        if (tmp && tmp.length > 0){
          for (let i = 0; i < tmp.length; i++){
            if(tmp[i].id == id){
              tmp.splice(i, 1)
            }
          }
        }   
        setState(state=>{
          return{
            ...state,
          buttonModal: {
            ...state.buttonModal,
            buttonList: {
              ...state.buttonModal.buttonList,
              data: tmp
            }
          }
          }
        })
        Message.success('删除成功')
        setState(state=>{
          return{
            ...state,
            buttonModal: {
              ...state.buttonModal,
              buttonList: {
                ...state.buttonModal.buttonList,
                loading: false
              }
            }
          }
        })
      },
      (eror)=>{
        Message.eror(eror)
        setState(state=>{
          return{
            ...state,
            buttonModal: {
              ...state.buttonModal,
              buttonList: {
                ...state.buttonModal.buttonList,
                loading: false
              }
            }
          }
        })
      })
  }

  //修改按钮权限
  function ButtonModify(){
    const [form] = Form.useForm();
    const [confirmLoading, setConfirmLoading] = useState(false);

    function submitButtonModify(){
      form.validate().then(data=>{
        fetchChangeModuleStatus({id: data.id, resName: data.resName, sort: data.sort, resKey: data.resKey },
          (res)=>{
            setConfirmLoading(true)
            let tmp = [...state.buttonModal.buttonList.data]
            if (tmp && tmp.length > 0){
              for (let i = 0; i < tmp.length; i++){
                if(tmp[i].id == data.id){
                  tmp[i] = {
                    ...tmp[i],
                    ...data
                  }
                }
              }
            }   
            setState(state=>{
              return{
                ...state,
              buttonModal: {
                ...state.buttonModal,
                buttonList: {
                  ...state.buttonModal.buttonList,
                  data: tmp
                }
              }
              }
            })
            Message.success('修改成功')
            setConfirmLoading(false)
            setButtonModify({
              ...buttonModify,
              visiable: false
          })
          },
          (error)=>{
            Message.error(error)
            setConfirmLoading(false)
          })
      }).catch(error=>{
        Message.error(error)
        setConfirmLoading(false)
      })
    }

    return(
        <Drawer
        width={414}
        title={<span>修改按钮权限列表 </span>}
        visible={buttonModify.visiable}
        confirmLoading={confirmLoading}
        onOk={() => {
          submitButtonModify()
        }}
        onCancel={() => {
            setButtonModify({
                ...buttonModify,
                visiable: false
            })
        }}
      >
         <Form {...formItemLayout} form={form} layout='vertical' >
         <Form.Item label='按钮id' field='id' initialValue={buttonModify.data ? buttonModify.data.id : null}>
            <Input disabled/>
          </Form.Item>
          <Form.Item label='按钮名称' required field='resName' 
           rules={[{ required: true , maxLength: 10, minLength: 2, message: '名称应该在2-10之间'}]}
           initialValue={buttonModify.data.resName}>
            <Input placeholder={buttonModify.data.resName}/>
          </Form.Item>
          <Form.Item label='排序数字' required field='sort' rules={[{ required: true }]}
            rules={[
              { required: true },
              { match: regExpConfig.isInt, message: '必须是数字' }
            ]}
            initialValue={buttonModify.data.sort}>
            <Input placeholder={buttonModify.data.sort}/>
          </Form.Item>
          <Form.Item label='关键字' required field='resKey' 
            rules={[
              { required: true, minLength: 3, maxLength: 10, message: '关键字应该为3-10个字符',},
              { match: regExpConfig.isNotChina, message: '必须为非中文字符' }
              ]}
           initialValue={buttonModify.data.resKey}>
           <Input placeholder={buttonModify.data.resKey}/>
          </Form.Item>
        </Form>
      </Drawer>
    )
  }
  //新增按钮
  function ButtonAdd(){
    const [form] = Form.useForm();
    const [confirmLoading, setConfirmLoading] = useState(false);

    function submitButtonAdd(){
      setConfirmLoading(true)
      form.validate().then((res) => {
        fetchModuleAdd({resName: res.resName, sort: res.sort, resKey: res.resKey},
          ()=>{
            // state.buttonModal.buttonList.data
            let tmp = [...state.buttonModal.buttonList.data]
            tmp.push({
              id: keyIterater,
              resName: res.resName,
              resType: 3,
              parentId: 4,
              roleEntities: [],
              resKey: res.resKey,
              sort: res.sort,
              status: 0,
            })
            next(keyIterater=>keyIterater+1)
            setState(state=>{
              return{
                ...state,
              buttonModal: {
                ...state.buttonModal,
                buttonList: {
                  ...state.buttonModal.buttonList,
                  data: tmp
                }
              }
              }
            })
            Message.success('添加成功')
            setConfirmLoading(false)
            setButtonAdd({
              ...buttonAdd,
              visiable: false
          })    
          },
          (error)=>{
            Message.error(error)
            setConfirmLoading(false)
          })
      }).catch(eror=>{
        Message.error(eror)
        setConfirmLoading(false)
      })
    }

    return(
        <Drawer
        width={414}
        title={<span>新增按钮 </span>}
        visible={buttonAdd.visiable}
        confirmLoading={confirmLoading}
        onOk={() => {
          submitButtonAdd()
        }}
        onCancel={() => {
            setButtonAdd({
                ...buttonAdd,
                visiable: false
            })
        }}
      >
         <Form {...formItemLayout} form={form} layout='vertical'>
          <Form.Item label='按钮名称' required field='resName' 
            rules={[{ required: true , maxLength: 10, minLength: 2, message: '名称应该在2-10之间'}]}>
            <Input placeholder='请输入按钮名称'/>
          </Form.Item>
          <Form.Item label='排序数字' required field='sort' 
            rules={[
              { required: true },
              { match: regExpConfig.isInt, message: '必须是数字' }
            ]}>
            <Input placeholder='请输入排序数字'/>
          </Form.Item>
          <Form.Item label='关键字' required field='resKey' rules={[{ required: true }]}>
          <Input placeholder='请输入关键字'/>
          </Form.Item>
        </Form>
      </Drawer>
    )
  }

    // 获取module列表
    function getButtonList(){
      setState(state=>{
        return{
          ...state,
          buttonModal: {
              ...state.buttonModal,
              buttonList: {
                ...state.buttonModal.buttonList,
                loading: true
              }
          }
      }
      })
      fetchButtonList({},
        (resp)=>{
          setState(state=>{
            return{
              ...state,
              buttonModal: {
                ...state.buttonModal,
                buttonList: {
                  ...state.buttonModal.buttonList,
                  loading: false,
                  data: resp.data.list
                }
              }
            }
          })
        },
        ()=>{
          setState(state=>{
            return{
              ...state,
              buttonModal: {
                ...state.buttonModal,
                buttonList: {
                  ...state.buttonModal.buttonList,
                  loading: false,
                  data: {}
                }
              }
            }
          })
        })
      // fetchModuleList({},
      //     (resp)=>{
      //         setState({
      //             ...state,
      //             moduleList: {
      //                 ...state.moduleList,
      //                 loading: false,
      //                 data: resp.data.list
      //             }
      //         })
      //     },
      //     ()=>{
      //     }
      // )
    }

  useEffect(()=>{
    getButtonList()
  },[])



  return (
    <div>
      <Drawer
        width={614}
        title={<span>模块按钮权限列表 </span>}
        footer={
            <>
                <Button type='primary'
                  onClick={()=>{
                    setButtonAdd({
                        ...buttonAdd,
                        visiable: true
                    })
                }}>新增</Button>
                <Button onClick={()=>{
                    setState(state=>{
                      return{
                        ...state,
                        buttonModal: {
                          ...state.buttonModal,
                          visible: false
                        }
                      }
                    })
                }}>取消</Button>
            </>
        }
        visible={state.buttonModal.visible}
        confirmLoading={confirmLoading}
        onCancel={() => {
          setState(state=>{
            return{
              ...state,
              buttonModal: {
                ...state.buttonModal,
                visible: false
              }
            }
          })
        }}
      >
        <div style={{padding: '20px'}}>
            <Table 
            loading={state.buttonModal.buttonList.loading}
            indentSize={60} 
            columns={columns} 
            data={state.buttonModal.buttonList.data} 
            borderCell='true'
            pagination={false}/>
        </div>
      </Drawer>
      { buttonModify.visiable ? <ButtonModify /> : null }
      <ButtonAdd />
    </div>
  );
}



export default ButtonModal